<template>
  <el-form
    class="login-form"
    status-icon
    :rules="loginRules"
    ref="loginForm"
    :model="loginForm"
    label-width="0"
  >
    <el-form-item v-if="tenantMode" prop="tenantId">
      <el-input
        size="small"
        @keyup.enter.native="handleLogin"
        v-model="loginForm.tenantId"
        auto-complete="off"
        :placeholder="$t('login.tenantId')"
      >
        <i slot="prefix" class="icon-quanxian"></i>
      </el-input>
    </el-form-item>
    <el-form-item prop="username">
      <el-input
        size="small"
        @keyup.enter.native="handleLogin"
        v-model="loginForm.username"
        auto-complete="off"
        :placeholder="$t('login.username')"
      >
        <i slot="prefix" class="icon-yonghu"></i>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        size="small"
        @keyup.enter.native="handleLogin"
        :type="passwordType"
        v-model="loginForm.password"
        auto-complete="off"
        :placeholder="$t('login.password')"
      >
        <i
          class="el-icon-view el-input__icon"
          slot="suffix"
          @click="showPassword"
        ></i>
        <i slot="prefix" class="icon-mima"></i>
      </el-input>
    </el-form-item>
    <el-form-item v-if="captchaMode" prop="code">
      <el-row :span="24">
        <el-col :span="16">
          <el-input
            size="small"
            @keyup.enter.native="handleLogin"
            v-model="loginForm.code"
            auto-complete="off"
            :placeholder="$t('login.code')"
          >
            <i slot="prefix" class="icon-yanzhengma"/>
          </el-input>
        </el-col>
        <el-col :span="8">
          <div class="login-code">
            <img
              :src="loginForm.image"
              class="login-code-img"
              @click="refreshCode"
            />
          </div>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        size="small"
        @click.native.prevent="handleLogin"
        class="login-submit"
      >{{ $t("login.submit") }}
      </el-button>
    </el-form-item>
    <el-row>
      <el-button @click="dialogVisible = true" size="small">注册账号</el-button>
      <el-button @click="forgetPaw" class="el-paw" size="small"
      >忘记密码
      </el-button
      >
    </el-row>
    -->
    <!-- 注册用户 -->
    <el-dialog
      title="账号注册"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <avue-form
        v-model="obj"
        :option="option"
        @submit="addUsers"
        @error="error"
        submitText="注册"
        ref="objForm"
      >
        <template slot-scope="{ row }" slot="input">
          <el-tag>{{ row }}</el-tag>
        </template>
      </avue-form>
    </el-dialog>
    <!-- 注册用户 -->
    <!--忘记密码-->
    <el-dialog title="忘记密码" :visible.sync="dialogFormVisible" :modal='false' :close-on-click-modal="false">
      <el-form :model="formPassword" @error="error">
        <el-form-item label="账号" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input v-model="formPassword.account" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input v-model="formPassword.phone" autocomplete="off"></el-input>
          </el-col>
          <el-button type="primary" @click="getSmsPhone" :disabled="!BtnStatus">
            {{BtnStatus?'获取验证码':`${countDownTime}秒后获取`}}
          </el-button>
        </el-form-item>
        <el-form-item label="验证码" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input v-model="formPassword.phoneCode" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input type="password" v-model="formPassword.password" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input type="password" v-model="formPassword.passwords" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="submit" @click="forgetPassword">确 定</el-button>
      </div>
    </el-dialog>
    <!--忘记密码-->
  </el-form>
</template>

<script>
  import {mapGetters} from "vuex";
  import website from "@/config/website";
  import {getCaptcha} from "@/api/user";
  import {addUser,getUserMessage,getUpdatePassword} from "@/api/system/user";
  import {getTopUrl} from "@/util/util";
  import {info} from "@/api/system/tenant";
  import form from "../../views/util/form.vue";
  import {smsPhone} from "@/api/sms/sms";
  import {isvalidatemobile} from "@/util/validate";

  export default {
    components: {form},
    name: "userlogin",
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.obj.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      return {
        BtnStatus: true,
        countDownTime: 120,
        sendMsgDisabled: false,
        dialogFormVisible: false,
        dialogVisible: false,
        tenantMode: website.tenantMode,
        captchaMode: website.captchaMode,
        loginForm: {
          //租户ID
          tenantId: "000000",
          //用户名
          username: "admin",
          //密码
          password: "admin",
          //账户类型
          type: "account",
          //验证码的值
          code: "",
          //验证码的索引
          key: "",
          //预加载白色背景
          image:
            "",
        },
        loginRules: {
          tenantId: [
            {required: false, message: "请输入租户ID", trigger: "blur"},
          ],
          username: [
            {required: true, message: "请输入用户名", trigger: "blur"},
          ],
          password: [
            {required: true, message: "请输入密码", trigger: "blur"},
            {min: 1, message: "密码长度最少为6位", trigger: "blur"},
          ],
        },
        passwordType: "password",
        obj: {},
        option: {
          //menuBtn: false,
          objForm: [],
          column: [
            {
              label: "账号",
              prop: "account",
              span: 20,
              row: true,
              rules: [
                {
                  required: true,
                  message: "请输入账号",
                  trigger: "blur",
                },
              ],
            },
            {
              label: "昵称",
              prop: "name",
              span: 20,
              row: true,
              rules: [
                {
                  required: true,
                  message: "请输入昵称",
                  trigger: "blur",
                },
              ],
            },
            {
              label: "手机号",
              prop: "phone",
              span: 20,
              row: true,
              rules: [
                {
                  required: true,
                  message: "请输入手机号",
                  trigger: "blur",
                },
              ],
            },
            {
              label: "密码",
              prop: "password",
              type:'password',
              span: 20,
              row: true,
              rules: [{validator: validatePass, trigger: "blur"}],
            },
            {
              label: "确认密码",
              prop: "oldpassword",
              type:'password',
              span: 20,
              row: true,
              rules: [{validator: validatePass2, trigger: "blur"}],
            },
          ],
        },
        formPassword: {
          account: '',
          phone: '',
          phoneCode: '',
          password: '',
          passwords: '',
        },
        formLabelWidth: '80px'
      };
    },
    created() {
      this.getTenant();
      this.refreshCode();
    },
    mounted() {

    },
    computed: {
      ...mapGetters(["tagWel"]),
    },
    props: [],

    methods: {
      getSmsPhone() {
        if (this.formPassword.account === '') {
          this.$message.error('请输入账号!');
          return;
        }
        var phone = this.formPassword.phone;
        var list = isvalidatemobile(phone);
        if (list.result === false) {
          this.$message.error(list.msg);
          return;
        }
        var account = this.formPassword.account;
        getUserMessage(account,phone).then((res) => {
          if (JSON.stringify(res.data.data) === '{}'){
            this.$message.error('该账号不存在!');
          }else {
            let endMsRes = (new Date()).getTime() + 120000;//2分钟
            //Setitem 为封装 localStoryge 方法
            localStorage.setItem('myEndTime', JSON.stringify(endMsRes));
            this.codeCountDown(endMsRes)
            smsPhone(phone).then((res) => {
              var data = JSON.stringify(res.data);
              if (JSON.parse(data).success === true) {
                this.$message({
                  message: '发送成功!',
                  type: 'success'
                });
              }
            });
          }
        });
      },
      created() {
        let myEndTime = localStorage.getItem('myEndTime');
        myEndTime && this.codeCountDown(myEndTime)
      },
      codeCountDown(endMsRes) {
        this.BtnStatus = false;
        this.countDownTime = Math.ceil((endMsRes - (new Date()).getTime()) / 1000)
        let time = setTimeout(() => {
          this.countDownTime--
          if (this.countDownTime < 1) {
            this.BtnStatus = true
            this.countDownTime = 60
            localStorage.removeItem('myEndTime')
            clearTimeout(time)
          } else {
            this.codeCountDown(endMsRes)
          }
        }, 1000)
      },
      refreshCode() {
        getCaptcha().then((res) => {
          const data = res.data.data;
          this.loginForm.key = data.key;
          this.loginForm.image = data.image;
        });
      },
      showPassword() {
        this.passwordType === ""
          ? (this.passwordType = "password")
          : (this.passwordType = "");
      },
      handleLogin() {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: "登录中,请稍后。。。",
              spinner: "el-icon-loading",
            });
            this.$store
              .dispatch("LoginByUsername", this.loginForm)
              .then(() => {
                this.$router.push({path: this.tagWel.value});
                loading.close();
              })
              .catch(() => {
                loading.close();
              });
          }
        });
      },
      addUsers(row, done) {
        row.password = this.$md5(row.password);
        var phone = row.phone;
        var list = isvalidatemobile(phone);
        if (list.result === false) {
          this.$message.error(list.msg);
          done();
          return;
        }
        addUser(row).then(
          () => {
            this.$message({
              type: "success",
              message: "注册成功!",
            });
            this.$refs.objForm.resetForm();
            done();
          },
          (error) => {
            window.console.log(error);
            this.$refs.objForm.resetForm();
            done();
          }
        );
        this.dialogVisible = false
      },
      forgetPaw() {
        this.dialogFormVisible = true;
        this.created();
      },
      forgetPassword() {
        if (this.formPassword.account === '') {
          this.$message.error('请输入账号!');
          return;
        }
        var phone = this.formPassword.phone;
        var list = isvalidatemobile(phone);
        if (list.result === false) {
          this.$message.error(list.msg);
          return;
        }
        if (this.formPassword.password === '') {
          this.$message.error('请输入密码!');
          return;
        }
        if (this.formPassword.passwords !== this.formPassword.password) {
          this.$message.error('两次输入密码不一致!');
          return;
        }
        var account = this.formPassword.account;
        getUserMessage(account,phone).then((res) => {
          if (res.data.data ===''){
            this.$message.error('该账号不存在!');
          }else {
            const row = {
              id: res.data.data.id,
              password: this.$md5(this.formPassword.password),
              phone: this.formPassword.phone,
              phoneCode: this.formPassword.phoneCode
            };
            getUpdatePassword(row).then(() => {
              this.$message({
                type: "success",
                message: "修改成功!",
              });
              this.dialogFormVisible = false;
              this.formPassword = {};
            },
            (error) => {
              window.console.log(error);
            }
            );
          }
        });
      },
      getTenant() {
        let domain = getTopUrl();
        // 临时指定域名，方便测试
        //domain = "https://bladex.vip";
        info(domain).then((res) => {
          const data = res.data;
          if (data.success && data.data.tenantId) {
            this.tenantMode = false;
            this.loginForm.tenantId = data.data.tenantId;
          }
        });
      },
    },
  };
</script>

<style>
  .el-paw {
    margin-left: 165px !important;
  }
</style>
